package com.ruoyi.file.service;

import com.alibaba.nacos.common.utils.IoUtils;
import com.aliyun.oss.OSS;
import com.aliyun.oss.model.PutObjectResult;
import com.ruoyi.file.config.AliYunOssConfig;
import com.ruoyi.file.config.MinioConfig;
import com.ruoyi.file.utils.FileUploadUtils;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

/**
 * 阿里云 oss 文件存储
 *
 * @author ruoyi
 */
@Primary
@Service
public class AliYunOssSysFileServiceImpl implements ISysFileService {
    @Autowired
    private OSS ossClient;
    @Autowired
    private AliYunOssConfig aliYunOssConfig;


    /**
     * 阿里云文件上传接口
     *
     * @param file 上传的文件
     * @return 访问地址
     * @throws Exception
     */
    @Override
    public String uploadFileForAvatar(MultipartFile file) throws Exception {
        InputStream inputStream = null;
        try {
            String fileName = FileUploadUtils.extractFilename(file);
            inputStream = file.getInputStream();
            System.out.println(ossClient);
            // 上传文件流。
            ossClient.putObject(aliYunOssConfig.getAvatarBucketName(), fileName, inputStream);
            return aliYunOssConfig.getAvatarUrl() + fileName;
        } catch (Exception e) {
            throw new RuntimeException("Minio Failed to upload file", e);
        } finally {
            IoUtils.closeQuietly(inputStream);
        }
    }


    /**
     * 阿里云文件上传接口
     *
     * @param file 上传的文件
     * @return 访问地址
     * @throws Exception
     */
    @Override
    public String uploadFileForConfig(MultipartFile file) throws Exception {
        InputStream inputStream = null;
        try {
            String fileName = FileUploadUtils.extractFilename(file);
            inputStream = file.getInputStream();
            System.out.println(ossClient);
            // 上传文件流。
            ossClient.putObject(aliYunOssConfig.getConfigBucketName(), fileName, inputStream);
            // 关闭OSSClient。
            //ossClient.shutdown();
            return aliYunOssConfig.getConfigUrl() + fileName;
        } catch (Exception e) {
            throw new RuntimeException("Minio Failed to upload file", e);
        } finally {
            IoUtils.closeQuietly(inputStream);
        }
    }
}
